#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Module Description:多语言处理工具集
# @Author: xulp
# @DateTime: 2020/5/20 15:08
import ast
from pyshare.dal.gameconfig.game_env import get_config_env_set
from framework.firefly_dc import runtime_logger as log


class LanguageUtils(object):
    """语言处理相关工具集"""

    @classmethod
    def check_default_lang(cls, app_id, check_obj=None):
        """检测目标对象是否包含了地区默认语言配置"""

        try:
            if not check_obj:
                return False

            if isinstance(check_obj, basestring):
                check_obj = ast.literal_eval(check_obj)

            default_lang = cls.get_default_lang(app_id)

            # 当前只检测字典和列表类型
            if isinstance(check_obj, dict):
                # in 判断要比 dict.has_key('key') 快, 且python3之后就没有has_key了
                return default_lang in check_obj.keys()
            elif isinstance(check_obj, list):
                # 当前暂不考虑列表元素类型不一致的情况，以后有需要再加
                if check_obj[0] and isinstance(check_obj[0], dict):
                    for element in check_obj:
                        if default_lang not in element.keys():
                            return False
                else:
                    return default_lang in check_obj
            return True

        except SyntaxError:
            return True
        except Exception as e:
            err_msg = 'Language detection is abnormal:app_id:{app_id},check_obj:{obj},exception:{except_msg}'.\
                format(app_id=app_id, obj=check_obj, except_msg=e.message)
            log.error(err_msg)
            return False

    @staticmethod
    def get_default_lang(app_id):
        """获取逻辑区域标识对应的默认语言"""
        try:
            languages = get_config_env_set('Languages')

            if isinstance(languages, list):
                # 2.9及之前版本,该字段类型为list。
                return languages[0]
            elif isinstance(languages, dict):
                # 3.0及以后版本
                return languages.get(str(app_id))[0]
            else:
                raise Exception('Please check ConfigEnvSet.Languages type')
        except Exception:
            raise Exception('Please check ConfigEnvSet.Languages configuration')

    @staticmethod
    def get_role_language_name(name_dict, language_code, app_id):
        """
        获取角色的语言名称
        :param name_dict: 名称字典
        :param language_code: 角色语言编码
        :param app_id:
        :return:
        """
        role_name = name_dict
        try:
            role_name = name_dict[language_code]
        except KeyError:
            # 没有对应语言, 全局配置表第一个默认
            lang = LanguageUtils.get_default_lang(app_id=app_id)
            role_name = name_dict[lang]
        # 字符串
        except ValueError:
            pass
        return role_name


if __name__ == '__main__':
    # json 语法规定 数组或对象之中的字符串必须使用双引号，不能使用单引号
    # 官网描述："A string is a sequence of zero or more Unicode characters, wrapped in double quotes, \
    # using backslash escapes"
    str_test1 = '{"en": "如月06号舰队en", "zh-cn": "如月06号舰队"}'
    str_test2 = "{'en': '如月06号舰队en', 'zh-cn': '如月06号舰队'}"
    str_test3 = '["zh-cn", "en", "zh-tw"]'
    str_test4 = '非多语言对象'
    str_test5 = u'11111'
    dict_test1 = {"en": "如月06号舰队en", "zh-cn": "如月06号舰队"}
    list_test1 = ["zh-cn", "en", "zh-tw"]
    list_test2 = [{'zh-cn': 1}, {'en': 2, 'zh-cn': 2}]
    list_test3 = []

    assert LanguageUtils.check_default_lang(app_id=1010, check_obj=str_test1)
    assert LanguageUtils.check_default_lang(app_id=1010, check_obj=str_test2)
    assert LanguageUtils.check_default_lang(app_id=1010, check_obj=str_test3)
    assert LanguageUtils.check_default_lang(app_id=1010, check_obj=str_test4)
    assert LanguageUtils.check_default_lang(app_id=1010, check_obj=str_test5)
    assert LanguageUtils.check_default_lang(app_id=1010, check_obj=dict_test1)
    assert LanguageUtils.check_default_lang(app_id=1010, check_obj=list_test1)
    assert LanguageUtils.check_default_lang(app_id=1010, check_obj=list_test2)
    assert not LanguageUtils.check_default_lang(app_id=1010, check_obj=list_test3)
